package org.example.springbootwork.controller;

import org.example.springbootwork.domain.User;
import org.example.springbootwork.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public ResponseEntity<String> insertUser(@RequestBody User user) {
        int result = userService.insertUser(user);
        if (result > 0) {
            return ResponseEntity.ok("操作成功");
        } else {
            return ResponseEntity.badRequest().body("操作失败");
        }
    }

    @PutMapping
    public ResponseEntity<String> updateUser(@RequestBody User user) {
        int result = userService.updateUser(user);
        if (result > 0) {
            return ResponseEntity.ok("操作成功");
        } else {
            return ResponseEntity.badRequest().body("操作失败");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Integer id) {
        int result = userService.deleteUser(id);
        if (result > 0) {
            return ResponseEntity.ok("操作成功");
        } else {
            return ResponseEntity.badRequest().body("操作失败");
        }
    }
}
